package dawn.util;

import java.util.Calendar;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ScheduleUtil {

    public static ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(
            1);

    /**
     * 封装了ScheduledThreadPoolExecutor的scheduleAtFixedRate
     * 对延时起动做了一些处理
     * 
     * @param command
     * @param startTime
     * @param period
     * @return
     */
    public static ScheduledFuture<?> addSchedule(Runnable command,
            Calendar startTime, long period) {
        return addSchedule(command, startTime, period, TimeUnit.MILLISECONDS);
    }

    public static ScheduledFuture<?> addSchedule(Runnable command,
            Calendar startTime, long period, TimeUnit unit) {
        long startInitialDelay = startTime.getTime().getTime()
                - System.currentTimeMillis();
        if (period <= 0) {
            try {
                throw new Exception("period is a negative");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        while (startInitialDelay < 0)
            startInitialDelay += period;

        return se.scheduleAtFixedRate(command, startInitialDelay, period, unit);
    }

}
